<?php

namespace app\admin\model\finance;

use think\Model;

class Subjects extends Model
{

    // 表名
    protected $name = 'finance_subjects';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'income',
        'spending',
        'balance',
    ];

    public static function init()
    {
        /**
         * @notes 删除前
         */
        self::beforeDelete(function ($row) {
            $income = Incomelog::where(['subjects_id' => $row->id])->count();
            $spending = Spendinglog::where(['subjects_id' => $row->id])->count();
            if (($income + $spending) > 0) {
                throw new \think\Exception("对不起，该账户已有关联数据，不可做删除操作!");
            }
        });
    }

    //总流入
    public static function getIncomeAttr($value, $data)
    {
        return Incomelog::where(['status' => 'audited', 'subjects_id' => $data['id']])->sum('amount');
    }

    //总流出
    public static function getSpendingAttr($value, $data)
    {
        return Spendinglog::where(['status' => 'audited', 'subjects_id' => $data['id']])->sum('amount');
    }

    //当前余额
    public static function getBalanceAttr($value, $data)
    {
        return self::getIncomeAttr($value, $data) - self::getSpendingAttr($value, $data);
    }
}
